package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class SlideshowWinnerIntermidRoundActivity extends BaseActivity implements
View.OnClickListener{
	private String tournamentID;
	private Integer roundSeq;
	private Integer totalCompetitorSize;
	private ArrayList<String> winnerIDList;
	private ArrayList<String> firstRoundWinnerIDList;
	private ArrayList<String> secondRoundWinnerIDList;
	private ArrayList<String> thirdoundWinnerIDList;
	private ArrayList<String> fourthRoundWinnerIDList;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// getIntent
		Intent intent = getIntent();
		tournamentID = intent.getStringExtra("tournamentID");
		roundSeq = intent.getIntExtra("roundSeq", 0);
		totalCompetitorSize = intent.getIntExtra("totalCompetitorSize", 0);
		firstRoundWinnerIDList = intent.getStringArrayListExtra("firstRoundWinnerIDList");
		secondRoundWinnerIDList = intent.getStringArrayListExtra("secondRoundWinnerIDList");
		thirdoundWinnerIDList = intent.getStringArrayListExtra("thirdoundWinnerIDList");
		fourthRoundWinnerIDList = intent.getStringArrayListExtra("fourthRoundWinnerIDList");
		
		// roundSeq 에 따라 셋팅
		switch(roundSeq) {
		case 1:
			winnerIDList = firstRoundWinnerIDList;
			break;
		case 2:
			winnerIDList = secondRoundWinnerIDList;
			break;
		case 3:
			winnerIDList = thirdoundWinnerIDList;
			break;
		case 4:
			winnerIDList = fourthRoundWinnerIDList;
			break;
		}
		
		// 데이터 셋팅
		setDataByThread();
	}
	
	private void setDataByThread() {
		// 여기서 쓰이는 것들
		final Handler myHandler = new Handler();
		final ProgressDialog progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						try {
							String question_content = null;
							String question_low_category = null;
							
							if (isNetworkAvailableAndNotice()) { // 네트워크 셋팅 되어 있어야 갖고옴
								getWinnerIDList();
								getQuestionContent(question_content, question_low_category);
							}
							
							// UI 셋팅
							setTotalData(question_content, question_low_category);
						} catch(Exception e) {
							Log.d("tag", e.toString());
						} finally {
							progressDialog.dismiss();
						}
					}
				});
			}
		};
		new Thread(runnable).start();
	}
	
	private void setTotalData(String question_content, String question_low_category) {
		// init
		List<ImageView> userImgList = new ArrayList<ImageView>(); // 진출자 사진 List
		Integer winnerIDListSize = 0;

		// 진출자 객체가 null 이거나 사이즈가 0,1 이거나
		if(winnerIDList == null || winnerIDList.size() <= 1) {// 진출자가 1명인경우? // 바로 complete로 가야지 일루 오면 안댐
			Log.d("tag", "잘못된 DB값.");
			return ;
		} else {
			winnerIDListSize = winnerIDList.size();
		}
		
		// 참가자 토탈인원이 0이라는 것은 첫 시작페이지라는 뜻
		if(totalCompetitorSize == 0) {
			totalCompetitorSize = winnerIDListSize;
		}
		
		// 진출자 사이즈에 따라 UI 처리가 다름
		if (winnerIDListSize == 2) { // 결승전
			// 레이아웃 셋팅
			setContentView(R.layout.loveto_select_winner_report_final);
			
			// 이미지 다운로드를 위해  // init
			userImgList.add( (ImageView) findViewById(R.id.userphoto_01) );
			userImgList.add( (ImageView) findViewById(R.id.userphoto_02) );
		} else { // 준준결승전, 준결승전
			
			if(winnerIDListSize <= 8) { // 8명 이하
				// 레이아웃 셋팅
				setContentView(R.layout.loveto_select_winner_report_8people);
				
				// 이미지 다운로드를 위해  // init
				userImgList.add( (ImageView) findViewById(R.id.userphoto_01) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_02) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_03) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_04) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_05) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_06) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_07) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_08) );
			} else { // 9명 이상
				// 레이아웃 셋팅
				setContentView(R.layout.loveto_select_winner_report_32people);
				
				// 이미지 다운로드를 위해  // init
				userImgList.add( (ImageView) findViewById(R.id.userphoto_01) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_02) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_03) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_04) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_05) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_06) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_07) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_08) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_01) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_02) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_03) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_04) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_05) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_06) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_07) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_08) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_09) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_10) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_11) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_12) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_13) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_14) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_15) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_16) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_17) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_18) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_19) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_20) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_21) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_22) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_23) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_24) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_25) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_26) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_27) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_28) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_29) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_30) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_31) );
				userImgList.add( (ImageView) findViewById(R.id.userphoto_32) );
			}
			
			// Round 글자 수정
			TextView textView = (TextView) findViewById(R.id.textView1);
			textView.setText(roundSeq+"ROUND 진출");
			textView = (TextView) findViewById(R.id.textView2);
			textView.setText(roundSeq+"ROUND 진출자");
			// 설명글 수정
			textView = (TextView) findViewById(R.id.explaination2Textview);
			textView.setText(roundSeq+"ROUND는 " +winnerIDListSize+ "명이 도전합니다.");
		}
		
		// common 셋팅
		// 설명글 수정
		TextView textView = (TextView) findViewById(R.id.explaination1Textview);
		textView.setText(totalCompetitorSize + "명중 "+winnerIDListSize+"명의 진출자가 탄생하였습니다!");
		// textview 셋팅
		if(question_content != null && question_low_category != null) {
			changeRound(); // 라운드숫자 이미지 셋팅
			
			textView = (TextView) findViewById(R.id.tourinfo_question); // 질문 셋팅
			textView.setText(question_content);
			textView = (TextView) findViewById(R.id.tourinfo_low_category); // 세부질문 셋팅
			textView.setText("["+question_low_category+"]");
		} else {
			RelativeLayout question_layout = (RelativeLayout) findViewById(R.id.question_layout);
			question_layout.setVisibility(View.INVISIBLE);
		}
		
		// 유저들 Image 다운로드 후 셋팅
		getAndSetImages(winnerIDListSize, winnerIDList, userImgList);
		
		// btn 클릭리스너 셋팅
		RelativeLayout btn_join_or_choice = (RelativeLayout) findViewById(R.id.btn_join_or_choice);
		btn_join_or_choice.setOnClickListener(this);
	}

	private void changeRound() {
		// TODO Auto-generated method stub
		ImageView imagView = (ImageView)findViewById(R.id.round_num);
		if(roundSeq == 1) {
			imagView.setImageResource(R.drawable.num_round_01);
		} else if(roundSeq == 2) {
			imagView.setImageResource(R.drawable.num_round_02);
		} else if(roundSeq == 3) {
			imagView.setImageResource(R.drawable.num_round_03);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_join_or_choice:
			Intent intent;
			if(roundSeq == 1) {
				intent = new Intent(SlideshowWinnerIntermidRoundActivity.this, SlideshowWinner1RoundActivity.class);
			} else {
				intent = new Intent(SlideshowWinnerIntermidRoundActivity.this, SlideshowWinner23RoundActivity.class);
			}
	  		intent.putExtra("tournamentID", tournamentID);
	  		intent.putExtra("roundSeq", roundSeq);
	  		intent.putExtra("totalCompetitorSize", totalCompetitorSize);
	  		intent.putStringArrayListExtra("firstRoundWinnerIDList", firstRoundWinnerIDList);
	  		intent.putStringArrayListExtra("secondRoundWinnerIDList", secondRoundWinnerIDList);
	  		intent.putStringArrayListExtra("thirdoundWinnerIDList", thirdoundWinnerIDList);
	  		intent.putStringArrayListExtra("fourthRoundWinnerIDList", fourthRoundWinnerIDList);
	  		
	  		startActivity(intent);
			break;
		}
	}

	private void getAndSetImages(Integer winnerIDListSize, List<String> winnerIDList, List<ImageView> userImgList) {
		// TODO Auto-generated method stub
		// 참가자사진 셋팅
		for(int i=0; i<winnerIDListSize; i++) {
			StringBuffer sb = new StringBuffer();
			sb.append(LovetoConstant.PHOTO_THUMB_URL);
			sb.append(winnerIDList.get(i));
			sb.append(".jpg");
			ImageDownloader imageDownloader = new ImageDownloader();// 사진 다운로드
			userImgList.get(i).setVisibility(View.VISIBLE);
			imageDownloader.download(sb.toString(), userImgList.get(i));
		}
	}

	// 진출자 아이디 갖고오기
		private void getWinnerIDList() {
			// TODO Auto-generated method stub
			if(winnerIDList != null) {
				return ;
			} else {
				winnerIDList = new ArrayList<String>();
			}
			
			try {
				String jsonText = JsonUtils
						.getStringFromUrl(LovetoConstant.SELECT_TOURNAMENT_ROUND_PARTICIPANTS + "?tournamentid=" + tournamentID+"&roundseq=" + (roundSeq));
				Log.d("tag", jsonText);
				JSONArray jsonArray = new JSONArray(jsonText);
				Integer jsonArrayLen = jsonArray.length();
				for(int i=0; i<jsonArrayLen; i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					winnerIDList.add(object.getString("roundparticipant_memberid"));
				}
				Log.d("tag", jsonText);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// 질문 가져오기
		private void getQuestionContent(String question_content, String question_low_category) {
			// TODO Auto-generated method stub
			try {
				String jsonText = JsonUtils
						.getStringFromUrl(LovetoConstant.SELECT_TOURNAMENT_QUESTION_CONTENT + "?tournamentid=" + tournamentID+"&roundseq=" + (roundSeq));
				Log.d("tag", jsonText);
				JSONArray jsonArray = new JSONArray(jsonText);
				JSONObject object = jsonArray.getJSONObject(0);
				question_content = object.getString("question_content"); // 질문
				question_low_category = object.getString("question_low_category"); // 세부질문
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(SlideshowWinnerIntermidRoundActivity.this)
		.setTitle("알림")
		.setMessage("초기 페이지로 갑니다. 가시겠습니까?")
		.setPositiveButton("예", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
		        // TODO Auto-generated method stub
				Intent intent = new Intent(SlideshowWinnerIntermidRoundActivity.this, JoinedTournamentListActivity.class);
		  		startActivity(intent);
		        finish();
			}
			
		})
		.setNegativeButton("아니요", null)
		.show();
	}
}
